import { messages } from "share/common";
import React from 'react';
import { connect } from 'react-redux'
import menuRoute from 'routes/menuRoute'
import { Button, Icon, Badge, Tabs, Table, message, Popconfirm, Radio, Spin, Switch } from 'antd'
import 'styles/budget-setting/budget-organization/budget-structure/budget-structure-detail.scss';
import SlideFrame from "components/slide-frame"
import AddAuthorization from './add-authorization'
import AddPayWay from './add-pay-way'
import companyAccountSettingService from './company-account-setting.service'
import ListSelector from 'components/list-selector'
import moment from 'moment'
import Condition from 'components/condition'
const { If } = Condition;
const TabPane = Tabs.TabPane;
const { Group } = Radio;

class BankAccountDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      updateState: false,
      saving: false,
      loading: true,
      editing: false,
      infoData: {},
      selectedRowKeys: [],
      showSlideFrame: false,    //控制授权侧拉
      visibleSlideFrame: false,  //控制付款方式侧拉
      updateParams: {},
      editParams: {},
      tabs: [
        { key: 'AUTHORIZATION', name: messages('pay-setting.key23'/*账户授权*/) },
        { key: 'APY_TYPE', name: messages('pay-setting.key22'/*付款方式*/) },
        { key: 'ASSIGN_COMPANY', name: messages('pay-setting.key78')/*付款公司授权*/ }
      ],
      typeData: {},
      data: [],
      tabsData: {
        AUTHORIZATION: {
          url: `/api/companyBankAuth/selectCompanyBankId`,
          rowSelection: null,
          columns:
            [
              { title: messages('pay-setting.key24'/*公司代码*/), dataIndex: 'companyCode', width: '16%' },
              { title: messages('pay-setting.key25'/*公司名称*/), dataIndex: 'companyName', width: '16%' },
              { title: messages('components.key63'/*部门编码*/), dataIndex: 'departmentCode', width: '16%' },
              {
                title: messages('pay-setting.key27'/*部门名称*/), dataIndex: 'departmentName', width: '16%'
              },
              { title: messages('pay-setting.key28'/*被授权员工*/), dataIndex: 'employeeName', width: '16%' },
              {
                title: messages('pay-setting.key13'/*有效日期从*/),
                dataIndex: 'authorizeDateFrom',
                width: '16%',
                render(recode) {
                  return recode ? moment(recode).local().format('YYYY-MM-DD') : "";
                }
              },
              {
                title: messages('pay-setting.key14'/*有效日期至*/), dataIndex: 'authorizeDateTo', width: '16%',
                render(recode) {
                  return recode ? moment(recode).local().format('YYYY-MM-DD') : "";
                }
              },
              {
                title: messages('pay-setting.key29'/*状态*/), dataIndex: 'isEnabled', width: '16%', render(enabled) {
                  return <Badge status={enabled ? 'success' : 'error'}
                                text={enabled ? messages('common.status.enable') : messages('common.status.disable')}/>
                }
              },
              {
                title: messages('common.operation'), dataIndex: 'id', width: '16%', render: (text, record) => (
                  <span>
                    <a onClick={(e) => this.handleEdit(e, record)}>{messages('common.edit')}</a>
                  </span>)
              }
            ]
        },
        APY_TYPE: {
          rowSelection: null,
          url: `/api/comapnyBankPayment/getByBankAccountId`,
          columns:
            [
              {
                title: messages('pay-setting.key21'/*付款方式类型*/), dataIndex: 'paymentMethodCategory',
                key: 'paymentMethodCategory',
                render: value => {
                  const { mappingList } = this.state;
                  let res = '';
                  mappingList.map(item => {
                    value === item.value && (res = item.label);
                  });
                  return res;
                }
              },
              {
                title: messages('pay-setting.key30'/*付款方式代码*/),
                dataIndex: 'paymentMethodCode',
                key: "paymentMethodCode"
              },
              { title: messages('pay-setting.key31'/*付款方式名称*/), dataIndex: 'description', key: "description" },
              {
                title: messages('common.operation'), dataIndex: 'id', render: (text, record) => (
                  <span>
                    <a onClick={(e) => this.handleEdit(e, record)}>{messages('common.edit')}</a>
                    <span className="ant-divider"/>
                    <Popconfirm
                      title="确认删除吗？"
                      onConfirm={(e) => this.deleteItem(e, record)}
                    >
                      <a>{messages('common.delete')}</a>
                    </Popconfirm>
                  </span>)
              }
            ]
        },
        ASSIGN_COMPANY: {
          rowSelection: null,
          url: '/api/companyBankAuth/paymentCompany/companyAuth/select',
          columns: [
            { title: messages('pay-setting.key79')/*被授权单据公司代码*/, dataIndex: 'companyCode' },
            { title: messages('pay-setting.key80')/*被授权单据公司名称*/, dataIndex: 'companyName' },
            { title: messages('common.status.enable')/*启用*/, dataIndex: 'enabled', render: (value, record) => (
                <Switch defaultChecked={value} onChange={checked => this.handleChangeSwitch(checked, record)} disabled={this.state.disabled}/>
              )
            }
          ]
        }
      },
      rowSelection: {
        type: 'checkbox',
        selectedRowKeys: [],
        onChange: this.onSelectChange,
      },
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      nowStatus: 'AUTHORIZATION',
      showListSelector: false,
      newData: [],
      addText: messages('pay-setting.key32'/*添加授权*/),
      newBankAccountPage: menuRoute.getRouteItem('new-bank-account', 'key'),
      bankAccountPageDetail: menuRoute.getRouteItem('bank-account-detail', 'key'),
      mappingList: [],
      disabled: false,
      radioValue: 'all',
      radioLoading: false,
      allLoading: false,
      assignLoading: false
    }
  }

  //选项改变时的回调，重置selection
  onSelectChange = selectedRowKeys => {
    let tabsData = this.state.tabsData;
    tabsData.APY_TYPE.rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ tabsData, selectedRowKeys });
  };

  componentWillMount() {
    this.getCompanyBankByCompanyBankId(this.props.params.companyBankId);
    this.getList();
    this.getMap();
  }

  getMap = () => {
    this.getSystemValueList(2105).then(res => {
      let temp = [];
      res.data.values.map(item => {
        temp.push({ label: item.messageKey, value: item.code, key: item.code })
      });
      this.setState({ mappingList: temp });
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  //根据companyBankId获取公司银行信息
  getCompanyBankByCompanyBankId(companyBankId) {
    companyAccountSettingService.getCompanyBankByCompanyBankId(companyBankId).then((response) => {
      response.data.enabled = response.data.enabled ? messages('common.status.enable') : messages('common.status.disable');
      response.data.openAddress = `${response.data.province}/${response.data.city}`;
      this.setState({
        infoData: response.data,
      })
    }).catch((e) => {
      message.error(e);
    })
  }

  getList = () => {
    const { tabsData, page, pageSize, nowStatus } = this.state, { params } = this.props;
    this.setState({ loading: true });
    let temp = {
      page, size: pageSize
    };
    nowStatus === 'ASSIGN_COMPANY' ? (temp.bankAccountId = params.companyBankId) : (temp.id = params.companyBankId);
    companyAccountSettingService.getBankAccountDetailList(tabsData[nowStatus].url, temp).then(response => {
      // response.data.map((item, index) => {
      //   item.nowStatus = item.id || index;
      // });
      this.setState({
        data: response.data,
        loading: false,
        pagination: {
          total: Number(response.headers['x-total-count']),
          onChange: this.onChangePager,
          current: this.state.page + 1
        }
      })
    }).catch(e => {
      this.setState({ loading: false });
      message.error(e.response.data.message);
    })
  };

  onChangePager = page => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1,
      }, () => {
        this.getList();
      })
  };

  //删除一个付款方式
  deleteItem = (e, record) => {
    companyAccountSettingService.deletePayWay(record.id).then(() => {
      message.success(messages('common.operate.success'));
      this.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  //渲染Tabs
  renderTabs = () => {
    return (
      this.state.tabs.map(tab => {
        return <TabPane tab={tab.name} key={tab.key}/>
      })
    )
  };

  //点击
  onChangeTabs = (key) => {
    this.setState({
      nowStatus: key,
      addText: key === 'AUTHORIZATION' ? messages('pay-setting.key32'/*添加授权*/) : messages('common.add'),
      data: [],
      pagination: {
        total: 0
      },
      page: 0
    }, () => {
      key === 'ASSIGN_COMPANY' && this.getDefaultRadio();
      this.getList();
    })
  };

  getDefaultRadio = () => {
    const { params } = this.props;
    this.setState({ radioLoading: true });
    companyAccountSettingService.getDefaultRadio(params.companyBankId).then(res => {
      this.setState({ radioLoading: false, radioValue: res.data.paymentAuthType });
    }).catch(e => {
      this.setState({ radioLoading: false });
      message.error(e.response.data.message)
    })
  };

  //新建
  handleNew = () => {
    const { nowStatus } = this.state;
    if (nowStatus === "AUTHORIZATION") {
      let companyBankId = this.props.params.companyBankId;
      this.setState({ updateParams: { companyBankId: companyBankId }, showSlideFrame: true });
    } else if(nowStatus === 'ASSIGN_COMPANY') {
      this.setState({ showListSelector: true });
    } else {
      let companyBankId = this.props.params.companyBankId;
      this.setState({ editParams: { companyBankId: companyBankId }, visibleSlideFrame: true });
    }
  };

  handleAdd = result => {
    const { params } = this.props;
    this.setState({ assignLoading: true });
    let temp = [];
    result.result.map(item => {
      temp.push({
        bankAccountId: params.companyBankId,
        companyId: item.id,
        companyCode: item.companyCode,
        companyName: item.name
      })
    });
    companyAccountSettingService.saveAddCompany(temp).then(() => {
      this.setState({ assignLoading: false, showListSelector: false }, () => {
        this.getList();
      });
    }).catch(e => {
      this.setState({ assignLoading: false });
      message.error(e.response.data.message);
    })
  };

  //编辑
  handleEdit = (e, record) => {
    if (this.state.nowStatus === "AUTHORIZATION") {
      let companyBankId = this.props.params.companyBankId;
      record = {
        ...record,
        companyBankId,
        company: [{ id: record.companyId, key: record.companyId, companyCode: record.companyCode }]
      };
      this.setState({ updateParams: record, showSlideFrame: true, });
    } else {
      let { companyBankId } = this.props.params;
      record.companyBankId = companyBankId;
      record.company = [{ id: record.companyId, key: record.companyId, companyCode: record.companyCode }];
      this.setState({ editParams: record, visibleSlideFrame: true, });
    }
  };

  handleCloseSlide = (params) => {
    if (this.state.nowStatus === "AUTHORIZATION") {
      this.setState({
        showSlideFrame: false
      }, () => {
        if (params) {
          this.getList();
        }
      })
    } else {
      this.setState({
        visibleSlideFrame: false
      }, () => {
        if (params) {
          this.getList();
        }
      })
    }
  };

  handleBack = () => {
    let path = menuRoute.getRouteItem('company-account-setting', 'key').url;
    this.context.router.push(path)
  };

  handleChangeRadio = e => {
    const { params } = this.props;
    let radioValue = e.target.value, disabled = true;
    if( radioValue === '03') {
      disabled = false;
    }
    this.setState({ radioLoading: true });
    companyAccountSettingService.saveDefaultRadio({
      bankAccountId: params.companyBankId,
      paymentAuthType: radioValue
    }).then(() => {
      this.setState({ radioValue, disabled, radioLoading: false });
    }).catch(e => {
      this.setState({ radioLoading: true });
      message.error(e.response.data.message);
    });
  };

  handleChangeSwitch = (checked, record) => {
    this.setState({ allLoading: true });
    companyAccountSettingService.updateEnable({enabled: checked, id: record.id}).then(() => {
      this.setState({ allLoading: false },() => {
        this.getList();
      });
    }).catch(e => {
      this.setState({ allLoading: true });
      message.error(e.response.data.message);
    })
  };

  render() {
    const {
      tabsData, loading, pagination, nowStatus, data, saving, showSlideFrame, updateParams, addText, visibleSlideFrame,
      editParams, disabled, radioValue, radioLoading, allLoading, showListSelector, assignLoading
    } = this.state;
    const { params, location } = this.props;
    return (
      <Spin spinning={allLoading}>
        <Tabs onChange={this.onChangeTabs} style={{ marginTop: 20 }}>
          {this.renderTabs()}
        </Tabs>
        <If value={nowStatus === 'ASSIGN_COMPANY'}>
          <Spin spinning={radioLoading}>
            <div style={{ fontWeight: '600', fontSize: '16px', lineHeight: '32px' }}>
              {messages('pay-setting.key81')/*授权该银行账号可支付的业务单据的所属公司*/}
            </div>
            <Group value={radioValue} onChange={this.handleChangeRadio}>
              <Radio value={'01'}>{messages('pay-setting.key82')/*同帐套公司*/}</Radio>
              <Radio value={'02'}>{messages('pay-setting.key83')/*本公司*/}</Radio>
              <Radio value={'03'}>{messages('pay-setting.key84')/*部分公司*/}</Radio>
            </Group>
          </Spin>
        </If>
        <div className="table-header">
          <div>
            <div className="table-header-title">{messages('pay-setting.key85',{arg1: pagination.total})/*共 {arg1} 条数据*/}</div>
            <div className="table-header-buttons">
              <Button type="primary" onClick={this.handleNew} loading={saving} disabled={disabled}>{addText}</Button>
            </div>
          </div>
        </div>
        <Table
          columns={tabsData[nowStatus].columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          bordered
          rowKey={record => { return record.id }}
          rowSelection={tabsData[nowStatus].rowSelection}
        />
        <a style={{ fontSize: '14px', paddingBottom: '20px' }} onClick={this.handleBack}>
          <Icon type="rollback" style={{ marginRight: '5px' }}/>返回
        </a>
        <SlideFrame
          title={!updateParams.id ? messages('pay-setting.key32'/*添加授权*/) : messages('pay-setting.key33'/*编辑授权*/)}
          show={showSlideFrame}
          content={AddAuthorization}
          afterClose={this.handleCloseSlide}
          onClose={() => this.setState({ showSlideFrame: false })}
          params={{ flag: showSlideFrame, record: updateParams }}
        />
        <SlideFrame
          title={!editParams.id ? messages('pay-setting.key34'/*添加付款方式*/) : messages('pay-setting.key35'/*编辑付款方式*/)}
          show={visibleSlideFrame}
          content={AddPayWay}
          afterClose={this.handleCloseSlide}
          onClose={() => this.setState({ visibleSlideFrame: false })}
          params={{ flag: visibleSlideFrame, record: editParams }}
        />
        <ListSelector
          visible={showListSelector}
          onOk={this.handleAdd}
          confirmLoading={assignLoading}
          onCancel={() => this.setState({ showListSelector: false })}
          type={'assign_company'}
          extraParams={{
            setOfBooksId: location.state.setOfBooksId,
            bankAccountId: params.companyBankId
          }}
        />
      </Spin>
    )
  }
}

BankAccountDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {}
}

export default connect(mapStateToProps)(BankAccountDetail);
